//
//  HiAugmentedWorldViewController.m
//  HiAugmentedWorld
//
//  Created by Jonathan Saggau on 4/12/10.
//  Copyright Sounds Broken inc. 2010. All rights reserved.
//

#import "HiAugmentedWorldViewController.h"
#import "LocationTools.h"

@implementation HiAugmentedWorldViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;
    
    picker.wantsFullScreenLayout = YES;
    
    //1:1.124.. = aspect ratio of the screen
    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, 1.0f, 1.12412f);
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self presentModalViewController:picker animated:NO];
    
    anglesLabel = [[UILabel alloc] initWithFrame:CGRectMake(10., 360., 300., 30.)];
    [anglesLabel setText:@"Hello augmented world!"];
    [anglesLabel setBackgroundColor:[UIColor clearColor]];
    [anglesLabel setTextColor:[UIColor whiteColor]];
    [anglesLabel setFont:[UIFont boldSystemFontOfSize:12]];
    
    marriotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10., 390., 300., 30.)];
    [marriotLabel setText:@"Hello augmented world!"];
    [marriotLabel setBackgroundColor:[UIColor clearColor]];
    [marriotLabel setTextColor:[UIColor whiteColor]];
    [marriotLabel setFont:[UIFont boldSystemFontOfSize:12]];    
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.x = viewFrame.origin.y = 0.0;
    UIView *overlayView = [[UIView alloc] initWithFrame:viewFrame];
    [overlayView addSubview:anglesLabel];
    [overlayView addSubview:marriotLabel];
    [overlayView bringSubviewToFront:anglesLabel];
    [overlayView bringSubviewToFront:marriotLabel];

    // Load the image to show in the overlay:
    UIImage *overlayGraphic = [UIImage imageNamed:@"dolphin.png"];
    overlayGraphicView = [[UIImageView alloc] initWithImage:overlayGraphic];
    overlayGraphicView.frame = CGRectMake(30, 100, 145, 145);
    [overlayView addSubview:overlayGraphicView];
    
    picker.cameraOverlayView = overlayView;
    [overlayView release];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager setDelegate:self];
    [locationManager startUpdatingHeading];
    [locationManager startUpdatingLocation];
}

- (void)updateUI
{
    CLLocation *marriot = [[LocationTools class] locationForMarker];
    float directionToMarker = [[LocationTools class] angleFromCoordinate:[self.currentLocation coordinate] toCoordinate:[marriot coordinate]];
    CLLocationDistance dist = [self.currentLocation distanceFromLocation:marriot];
    
    double deltaAlt = [marriot altitude] - [self.currentLocation altitude];
    
    //verticalAccuracy of -1 == invalid
    if ([self.currentLocation verticalAccuracy] < 0)
    {
        deltaAlt = 0;
    }
    
    double vertAngleToMarker = atan2(deltaAlt, dist);
    
    [marriotLabel setText:[NSString stringWithFormat:@"DirHotel:%5.1f Dist: %5f VertAngle: %f", 
                                                       directionToMarker * (180.0 / M_PI), dist, vertAngleToMarker * (180.0 / M_PI)]];
    
    [anglesLabel setText: [NSString stringWithFormat:@"Horizon H-Angle:%5.1f V-Angle:%5.1f Heading:%5.1f", 
                     angleInDeg, vertAngleInDeg, magCompassHeadingInDeg]];
    
    double relativeDirectionToMarker =  magCompassHeadingInDeg * (M_PI / 180.) - directionToMarker;
    
    if (relativeDirectionToMarker < (-M_PI / 2.0)) {
        relativeDirectionToMarker = (-M_PI / 2.0); 
    }
    
    if (relativeDirectionToMarker > (M_PI / 2.0)) {
        relativeDirectionToMarker = (M_PI / 2.0); 
    }
    
    double relativeVertAngleToMarker = vertAngleToMarker - vertAngle;
    
    CGPoint overlayCenter = [overlayGraphicView center];
    overlayCenter.y = 240.0 - 537.8 * sin(relativeVertAngleToMarker);    
    overlayCenter.x = 160.0 - 497.8 * sin(relativeDirectionToMarker);
    [overlayGraphicView setCenter:overlayCenter];  
    
//    NSLog(@"center = %@", NSStringFromCGPoint(overlayCenter));
    
    overlayGraphicView.transform = CGAffineTransformMakeRotation(angle);
}

#pragma mark UIAccelerometerDelegate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration;
{
    vertAngle = atan2(acceleration.y, acceleration.z) + M_PI/2.0;
    vertAngleInDeg = vertAngle * 180.0f/M_PI;
    
    angle = -atan2(acceleration.y, acceleration.x) - M_PI/2.0;
    angleInDeg = angle * 180.0f/M_PI;
    [self updateUI];
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading;
{
    magCompassHeadingInDeg = [newHeading magneticHeading];
    [self updateUI];
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;
{
    //NSLog(@"%@ %s toLocation:%@ fromLocation:%@", self, _cmd, newLocation, oldLocation);
    NSLog(@"Height: %f", [newLocation altitude]);
    
    [self setCurrentLocation:newLocation];
    [self updateUI];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

@synthesize currentLocation;

- (void)dealloc {
    [[UIAccelerometer sharedAccelerometer] setDelegate:nil];
    [locationManager stopUpdatingHeading]; 
    
    [currentLocation release]; currentLocation = nil;
    [locationManager release]; locationManager = nil;
    [anglesLabel release]; anglesLabel = nil;
    [overlayGraphicView release]; overlayGraphicView = nil;
    [super dealloc];
}

@end





/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */
